import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
// import 'package:flutter/services.dart';
// import 'package:flutter_community/stores/counter.dart';
import 'package:flutter_community/utils/eventBus.dart';
import 'package:flutter_community/utils/http.dart';
import 'package:flutter_community/utils/showToast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
// import 'package:provider/provider.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key, required this.userInfo});
  //传递用户信息
  final Map userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  Map userInfo = {
    'id': '',
    'avatar': '',
    'nickName': '',
  };
  final TextEditingController _nickNameController = TextEditingController();
  @override
  void initState() {
    super.initState();
    //获取用户信息
    setState(() {
      userInfo = widget.userInfo;
      _nickNameController.text =
          userInfo['nickName'] == '' ? '' : userInfo['nickName'];
    });
  }

//修改用户信息
  _updateInfo() async {
    //获取用户昵称
    final nickName = _nickNameController.text;
    if (nickName == '') {
      return ToastMessage.showFail('请输入昵称');
    }
    if (nickName.length > 10) {
      return ToastMessage.showFail('昵称过长');
    }
    await http.put('/userInfo', data: {'nickName': nickName});
    ToastMessage.showSuccess('修改成功');
  }

  // //判断是否授权
  // Future<void> requestLocationPermission() async {
  //   PermissionStatus status = await Permission.camera.request();
  //   if (status.isGranted) {
  //     // 权限未授予
  //     ToastMessage.showSuccess('相机权限授予');
  //   } else {
  //     // 权限未授予
  //     ToastMessage.showFail('位置权限未授予, 请去设置中心开启');
  //   }
  // }

//拉起底部弹窗
  _showBottomSheet() {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
            height: 180,
            child: Column(
              children: [
                ListTile(
                  //左边图标
                  leading: const Icon(Icons.camera_alt),
                  title: const Text('拍照'),
                  //右边图标
                  trailing: const Icon(Icons.arrow_forward_ios_outlined),
                  onTap: () async {
                    try {
                      // //授权检测
                      // await requestLocationPermission();
                      //创建图片选择器对象
                      final ImagePicker picker = ImagePicker();
                      //拉起相机
                      final XFile? photo =
                          await picker.pickImage(source: ImageSource.camera);

                      if (photo != null) {
                        upLoadAvatar(photo.path);
                      }
                    } catch (e) {
                      print('错误$e');
                    }
                  },
                ),
                ListTile(
                  //左边图标
                  leading: const Icon(Icons.photo),
                  title: const Text('相册'),
                  //右边图标
                  trailing: const Icon(Icons.arrow_forward_ios_outlined),
                  onTap: () async {
                    //创建图片选择器对象
                    final ImagePicker picker = ImagePicker();
                    //获取图片
                    final XFile? image =
                        await picker.pickImage(source: ImageSource.gallery);
                    if (image != null) {
                      //上传图片
                      upLoadAvatar(image.path);
                    }
                  },
                ),
              ],
            ),
          );
        });
  }

  //上传头像
  upLoadAvatar(String imgPath) async {
    // ToastMessage.showSuccess(imgPath);
    try {
      // 1.创建formData
      FormData formData = FormData.fromMap({
        "file": kIsWeb
            ? MultipartFile.fromBytes(
                await XFile(imgPath).readAsBytes(),
                filename: 'avatar.jpg',
                contentType: DioMediaType('image', 'jpeg'),
              )
            : MultipartFile.fromFileSync(imgPath),
        'type': 'avatar'
      });
      // 2.调用上传接口
      final res = await http.post('/upload', data: formData);
      setState(() {
        // 3.更新用户信息
        userInfo['avatar'] = res['data']['url'];
        ToastMessage.showSuccess('上传成功');
      });
    } catch (e) {
      ToastMessage.showFail('上传失败');
    } finally {
      // 关闭底部弹窗
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '个人信息',
          style: TextStyle(fontSize: 20),
        ),
        backgroundColor: Colors.transparent,
        centerTitle: true,
        //自定义返回按钮
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            Navigator.pop(context);
            eventBus.fire(EditInfoRefreshEvent());
          },
        ),
      ),
      body: Container(
        padding: const EdgeInsets.all(10),
        child: Column(
          children: [
            GestureDetector(
              onTap: () {
                //点击拉起底部弹层
                _showBottomSheet();
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text('头像'),
                  Row(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(20),
                        child: userInfo['avatar'] == ''
                            ? Image.asset(
                                'assets/images/avatar_1.jpg',
                                width: 40,
                                height: 40,
                              )
                            : Image.network(
                                userInfo['avatar'],
                                width: 40,
                                height: 40,
                              ),
                      ),
                      const SizedBox(width: 10),
                      const Icon(Icons.arrow_forward_ios, size: 12)
                    ],
                  )
                ],
              ),
            ),
            const SizedBox(height: 10),
            //昵称
            Row(
              children: [
                const Text('昵称'),
                Expanded(
                  child: TextField(
                    controller: _nickNameController,
                    decoration: const InputDecoration(
                        hintStyle: TextStyle(fontSize: 14),
                        hintText: '请输入昵称',
                        border: InputBorder.none),
                    textAlign: TextAlign.right,
                    //输入完成后触发
                    onEditingComplete: () {
                      setState(() {
                        _updateInfo();
                      });
                    },
                  ),
                ),
                const Icon(Icons.arrow_forward_ios, size: 12)
              ],
            )
          ],
        ),
      ),
    );
  }
}
